﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using System.Threading;

using BartonExtension;
using Model.Weixin;
using Model.App;
using Model.Images;

using Cache.Model;
using Cache.Utils;
using Cache;

using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin;

namespace iShangMai
{
    public static class AccessTokenHelper
    {
        public static Task<AccessToken> tokenFromCacheAsync(string openid)
        {
            return CacheManager.instance.objectFromCacheAsync<AccessToken>(openid);
        }
        public static CachingResult<object> cacheToken(this AccessToken token)
        {
            return CacheManager.instance.doCacheObject<object>(token, token.openid);
        }
        public static string GetAuthUrl(string state, string redirectUrl)
        {
            return OAuthApi.GetAuthorizeUrl(Constants.appId, redirectUrl, state, OAuthScope.snsapi_userinfo);
        }

        public static AccessToken GetAccessTokenFromWeixinService(string code)
        {
            try
            {
                OAuthAccessTokenResult weixin_token = OAuthApi.GetAccessToken(Constants.appId, Constants.secret, code);
                if (weixin_token.errcode != ReturnCode.请求成功)
                {
                    return null;
                }

                AccessToken acs_token = new AccessToken()
                {
                    access_token = weixin_token.access_token,
                    openid = weixin_token.openid,
                    createTime = DateTime.Now,
                    expiredTime = weixin_token.expires_in,
                    refresh_token = weixin_token.refresh_token
                };
                return acs_token;
            }
            catch(Exception e)
            {
                return null;
            }
        }

        public static Task<AccessToken> GetAccessToken(string state,string code)
        {
            
            return Task.Factory.StartNew<AccessToken>(()=>
                {
                    AccessToken acs = AccessTokenHelper.GetAccessTokenFromWeixinService(code);
                    return acs;
                });
        }
    }
}